package org.kotemaru.gae.dstool.client.gui;
import org.apache.commons.beanutils.BeanUtils;
import org.kotemaru.browser.*;
import org.kotemaru.gae.dstool.client.*;
import java.io.*;
import java.util.*;

public class MainAction extends ActionBase {
	static final String DSTOOL_PROPS = DsToolClient.DSTOOL_PROPS;

	private String appid;
	private String kind;
	private String file;
	private String submit;
	
	public Navigator execute() throws Exception {
		if (submit == null) {
			Properties props = ClientUtil.loadProps(DSTOOL_PROPS, null, false);
			BeanUtils.copyProperties(this, props);
			return velocity("main.vm");
		} else {
			PrintStream backupErr = System.err;
			try {
				System.setErr(new StderrLogger(super.takeBrowserFrame()));
				return doSubmit();
			} finally {
				System.setErr(backupErr);
			}

		}
	}
		
	private Navigator doSubmit() throws Exception {
		appid = ClientUtil.correntAppid(appid);
		String url = "https://"+appid+".appspot.com/dstool";
		int limit = 100;
		Properties props = ClientUtil.loadProps(DSTOOL_PROPS, null, false);
		GaeOAuthClient client = new GaeOAuthClient(props);
		
		if ("Download".equals(submit)) {
			Writer writer = ClientUtil.takeWriter(file);
			EntityDownloader dler = new EntityDownloader(client, writer, url, kind);
			dler.setLimit(limit);
			dler.download();
		} else if ("Upload".equals(submit)) {
			Reader reader = ClientUtil.takeReader(file);
			EntityUploader uler = new EntityUploader(client, url, kind);
			uler.setLimit(limit);
			uler.upload(reader);
		}

		//BeanUtils.copyProperties(props, this);
		props.setProperty("appid", appid);
		props.setProperty("kind", kind);
		props.setProperty("file", file);
		System.out.println("-->"+props);
		ClientUtil.saveProps(DSTOOL_PROPS, props);
		return null;
	}


//-------------------------------------------------------
// Setter/Getter
	public String getAppid() {
		return appid;
	}

	public void setAppid(String appid) {
		this.appid = appid;
	}

	public String getKind() {
		return kind;
	}

	public void setKind(String kind) {
		this.kind = kind;
	}

	public String getFile() {
		return file;
	}

	public void setFile(String file) {
		this.file = file;
	}


	public String getSubmit() {
		return submit;
	}


	public void setSubmit(String submit) {
		this.submit = submit;
	}

	

}
